
package com.rohoo.framework.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.rohoo.framework.util.ResultSetUtil;

/**
 * Base DAO Class, 业务系统的DAO�?��继承BaseDAO
 * 
 * @author shaoyifeng
 * 
 */
public abstract class BaseDAO extends JdbcDaoSupport {

	/** logger4j日志，子类可以直接使�?*/
    protected Logger logger = Logger.getLogger(getClass());

	//-- Public Methods -----------------------------------------------------//

	/**
	 * 分页查询 
	 * @param querySql     查询语句，包含排�?
	 * @param countSql     查询记录数统计语�?
	 * @param target       数据库记录包装类
	 * @param currentPage  结果当前页数
	 * @param pageSize     结果每页条数
	 * @return 结果集合
	 */
	public DataPackage getPage(String querySql, String countSql, final Class target, int currentPage, int pageSize)
			throws DataAccessException {
		int iCurPage = adjustCurrentPage(currentPage);
		final int iPageSize = adjustPageSize(pageSize);

		if (countSql == null) {
			countSql = "select count(*) " + querySql.substring(querySql.indexOf(" from "));
		}

		final int iTotalCount = getJdbcTemplate().queryForInt(countSql);
		final int iStartRowNum = (iCurPage - 1) * iPageSize;
		List result = getJdbcTemplate().query(querySql, new RowMapper() {
			public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
				if (iStartRowNum <= rowNum && rowNum < iStartRowNum + iPageSize) {
					return ResultSetUtil.getElement(target, rs);
				}
				else {
					return null;
				}
			}
		});
		List thisPageResult = new ArrayList();
		for (Iterator iter = result.iterator(); iter.hasNext();) {
			Object element = iter.next();
			if (element != null) {
				thisPageResult.add(element);
			}
		}

		return wrapperPageableResult(iTotalCount, thisPageResult, iCurPage, iPageSize);
	}

	//-- Private Methods ----------------------------------------------------//

	private static int adjustCurrentPage(Integer currentPage) {
		int iCurPage = 1;
		if (currentPage != null && currentPage.intValue() > 0) {
			iCurPage = currentPage.intValue();
		}
		return iCurPage;
	}

	private static int adjustPageSize(Integer pageSize) {
		int iPageSize;

		if (pageSize != null && pageSize.intValue() > 0) {
			iPageSize = pageSize.intValue();
		}
		else {
			iPageSize = 10;
		}

		return iPageSize;
	}

	/**
	 * @param totalCount
	 * @param result
	 * @param curPage
	 * @param pageSize
	 * @return
	 */
	private DataPackage wrapperPageableResult(int iTotalCount, List result, int iCurPage, int iPageSize) {
		int iResultCount = 0;
		if (result != null) {
			iResultCount = result.size();
		}

		int remainder = 0; //尾页判断
		if (iTotalCount % iPageSize != 0) {
			remainder = 1;
		}

		DataPackage dp = new DataPackage();
		dp.setPageLines(iPageSize);
		dp.setCurrPage(iCurPage);
		dp.setRowCount(iTotalCount);

		if (iResultCount == 0) //无结果集
		{
			dp.setRowList(new ArrayList());
		}
		else {
			dp.setRowList(result);

		}

		return dp;
	}

	private int adjustPageSize(int pageSize) {
		int iPageSize;
		if (pageSize > 0) {
			iPageSize = pageSize;
		}
		else {
			iPageSize = 10;
		}
		return iPageSize;
	}

	private int adjustCurrentPage(int currentPage) {
		if (currentPage > 0) {
			return currentPage;
		}
		else {
			return 1;
		}
	}

	//------------------------------------------------------//
	public HashMap getPagedHashMap(String querySql, String countSql, final Class target, int currentPage, int pageSize)
			throws DataAccessException {
		int iCurPage = adjustCurrentPage(currentPage);
		final int iPageSize = adjustPageSize(pageSize);

		if (countSql == null) {
			countSql = "select count(*) " + querySql.substring(querySql.indexOf(" from "));
		}

		final int iTotalCount = getJdbcTemplate().queryForInt(countSql);
		final int iStartRowNum = (iCurPage - 1) * iPageSize;
		List result = getJdbcTemplate().query(querySql, new RowMapper() {
			public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
				if (iStartRowNum <= rowNum && rowNum < iStartRowNum + iPageSize) {
					return ResultSetUtil.getElement(target, rs);
				}
				else {
					return null;
				}
			}
		});
		List thisPageResult = new ArrayList();
		for (Iterator iter = result.iterator(); iter.hasNext();) {
			Object element = iter.next();
			if (element != null) {
				thisPageResult.add(element);
			}
		}

		return wrapperHashMapResult(iTotalCount, thisPageResult, iCurPage, iPageSize);
	}

	/**
	 * @param totalCount
	 * @param result
	 * @param curPage
	 * @param pageSize
	 * @return
	 */
	private HashMap wrapperHashMapResult(int iTotalCount, List result, int iCurPage, int iPageSize) {
		int iResultCount = 0;
		if (result != null) {
			iResultCount = result.size();
		}
		int remainder = 0; //尾页判断
		if (iTotalCount % iPageSize != 0) {
			remainder = 1;
		}

		Integer countPage = new Integer(iTotalCount / iPageSize + remainder);
		Integer currentPageTemp = new Integer(iCurPage);
		Integer countPerPageTemp = new Integer(iPageSize);
		Integer totalCount = new Integer(iTotalCount);

		HashMap pageMap = new HashMap();
		pageMap.put("totalpage", countPage);
		pageMap.put("currentpage", currentPageTemp);
		pageMap.put("countperpage", countPerPageTemp);
		pageMap.put("totalcount", totalCount);

		if (iResultCount == 0) //无结果集
		{
			pageMap.put("RESULT", new ArrayList());
		}
		else {
			pageMap.put("RESULT", result);

		}
		/*if (logger.isDebugEnabled()) {
			logger.debug("DAO multi pages sql getHashCollection:");
			logger.debug("... totalpage=" + countPage);
			logger.debug("... currentpage=" + currentPageTemp);
			logger.debug("... countperpage=" + countPerPageTemp);
			logger.debug("... RESULT size=" + iResultCount);
		}
*/
		return pageMap;
	}

}
